package org.example.DAO;
import org.example.entity.Like;
import org.example.DAO.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

public class LikeDAO {
    private final Connection conn;

    public LikeDAO(Connection conn) {
        this.conn = conn;
    }

    public Boolean getUserBlogLikeStatus(Integer userId, String blogId) throws SQLException {
        String sql = "SELECT TYPE FROM `Like` WHERE USERID = ? AND BLOGID = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            stmt.setString(2, blogId);
            ResultSet rs = stmt.executeQuery();
            return rs.next() ? rs.getBoolean("TYPE") : null;
        }
    }

    public int[] getBlogLikes(String blogId) throws SQLException {
        String likeSql = "SELECT COUNT(*) FROM `Like` WHERE BLOGID = ? AND TYPE = 1";
        String dislikeSql = "SELECT COUNT(*) FROM `Like` WHERE BLOGID = ? AND TYPE = 0";
        int[] counts = new int[2];

        try (PreparedStatement stmt = conn.prepareStatement(likeSql)) {
            stmt.setString(1, blogId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) counts[0] = rs.getInt(1);
        }

        try (PreparedStatement stmt = conn.prepareStatement(dislikeSql)) {
            stmt.setString(1, blogId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) counts[1] = rs.getInt(1);
        }
        return counts;
    }

    // 添加删除点赞方法
    public boolean deleteLikeByUserAndBlog(Integer userId, String blogId) throws SQLException {
        String sql = "DELETE FROM `Like` WHERE USERID = ? AND BLOGID = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            stmt.setString(2, blogId);
            return stmt.executeUpdate() > 0;
        }
    }

    // 添加点赞方法
    public boolean addLike(Like like) throws SQLException {
        String sql = "INSERT INTO `Like` (LIKEID, BLOGID, USERID, TYPE, CREATED_AT) VALUES (?, ?, ?, ?, ?)";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, UUID.randomUUID().toString());
            stmt.setString(2, like.getBlogId());
            stmt.setInt(3, like.getUserId());
            stmt.setBoolean(4, like.isType());
            stmt.setTimestamp(5, new java.sql.Timestamp(System.currentTimeMillis()));
            return stmt.executeUpdate() > 0;
        }
    }
}